package vertx.starter.refactor;

import io.vertx.core.AbstractVerticle;
import io.vertx.core.Promise;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.http.HttpServer;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.Router;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.BodyHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class HttpServerVerticle extends AbstractVerticle {

  private static final
  Logger LOGGER = LoggerFactory.getLogger(HttpServerVerticle.class);

  public static final String CONFIG_HTTP_SERVER_PORT = "http.server.port";
  public static final String CONFIG_WIKIDB_QUEUE = "wikidb.queue";

  private String wikiDbQueue = "wikidb.queue";


  @Override
  public void start(Promise<Void> promise) throws Exception {

    wikiDbQueue = config().getString(CONFIG_WIKIDB_QUEUE, "wikidb.queue");

    Router router = Router.router(vertx);
    // router.get("/").handler(this::indexHandler);
    router.get("/page").handler(this::queryHandler);
    router.post().handler(BodyHandler.create());
    router.post("/create").handler(this::pageCreateHandler);
    router.delete("/").handler(this::deleteHandler);

    int port = config().getInteger(CONFIG_HTTP_SERVER_PORT, 8089);
    HttpServer server = vertx.createHttpServer();
    server
      .requestHandler(router)
      .listen(port, ar -> {
        if (ar.succeeded()) {
          LOGGER.info("HTTP server running on port: " + port);
          promise.complete();
        } else {
          LOGGER.error("Could not start a HTTP server", ar.cause());
          promise.fail(ar.cause());
        }
      });

  }

  private void deleteHandler(RoutingContext routingContext) {
    DeliveryOptions options = new DeliveryOptions().addHeader("action", "delete-page");

    JsonObject entries = new JsonObject();
    List<String> stringList = routingContext.queryParam("name");
    if(stringList !=null && !stringList.isEmpty() )
    entries.put("name", stringList.get(0));
    vertx.eventBus().request(wikiDbQueue, entries, options, relpy -> {
      if (relpy.succeeded()) {
        Object body = relpy.result().body();
        routingContext.response().putHeader("Content-Type", "application/json").end(body.toString());

      } else {
        routingContext.fail(relpy.cause());
      }

    });
  }

  private void pageCreateHandler(RoutingContext context) {
    DeliveryOptions options = new DeliveryOptions().addHeader("action", "create-page");

    vertx.eventBus().request(wikiDbQueue, context.getBodyAsJson(), options, reply -> {
      if (reply.succeeded()) {
        Object body = reply.result().body();
        context.response().putHeader("Content-Type", "application/json");
        context.response().end(body.toString());
      } else {
        context.fail(reply.cause());
      }
    });
  }

  private void queryHandler(RoutingContext context) {
    DeliveryOptions options = new DeliveryOptions().addHeader("action", "all-pages");

    vertx.eventBus().request(wikiDbQueue, new JsonObject(), options, reply -> {
      if (reply.succeeded()) {
        JsonObject body = (JsonObject) reply.result().body();
        context.response().putHeader("Content-Type", "application/json");
        context.response().end(body.toString());

      } else {
        context.fail(reply.cause());
      }
    });
  }


}
